package com.salmon.oss.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import javax.annotation.Resource;
import javax.validation.Valid;

import com.salmon.oss.common.AjaxResult;
import com.salmon.oss.common.RegexUtill;
import com.salmon.oss.entity.Peers;
import org.iq80.leveldb.DB;
import org.iq80.leveldb.DBException;
import org.iq80.leveldb.impl.Iq80DBFactory;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping({"/cluster"})
public class LevelDBController {
    public static final String FASTDFS_SERVER_ADDRESS = "fastdfs_peers_address";
    public static final byte[] FASTDFS_SERVER_ADDRESS_BYTES = Iq80DBFactory.bytes(FASTDFS_SERVER_ADDRESS);

    @Resource(name = "levelDB")
    private DB levelDB;

    @RequestMapping({"/add"})
    public AjaxResult doAdd(@Valid Peers peers, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return new AjaxResult(500, bindingResult.getFieldError().getDefaultMessage());
        } else if (!RegexUtill.verifyUrl(peers.getServerAddress())) {
            return new AjaxResult(500, "对象存储服务服务地址填写错误!");
        } else {
            String peersUrl;
            try {
                String urlPath = peers.getServerAddress();
                if (StrUtil.isNotBlank(peers.getGroupName())) {
                    urlPath = urlPath + "/" + peers.getGroupName();
                }

                peersUrl = HttpUtil.get(urlPath + "/stat");
                JSONObject parseObj = JSONUtil.parseObj(peersUrl);
                if (!parseObj.get("status").equals("ok")) {
                    return new AjaxResult(500, "测试连接对象存储服务服务失败!请检查该服务地址是否已配置白名单!");
                }
            } catch (Exception var7) {
                return new AjaxResult(500, "测试连接对象存储服务服务失败!请检查该服务地址是否正确!");
            }

            byte[] bytes = this.levelDB.get(FASTDFS_SERVER_ADDRESS_BYTES);
            peersUrl = Iq80DBFactory.asString(bytes);
            if (StrUtil.equals(peers.getServerAddress(), peersUrl)) {
                return new AjaxResult(500, "该集群已存在!");
            } else {
                try {
                    this.levelDB.put(FASTDFS_SERVER_ADDRESS_BYTES, Iq80DBFactory.bytes(JSONUtil.toJsonStr(peers)));
                    return new AjaxResult(200);
                } catch (DBException var6) {
                    return new AjaxResult(500, var6.getMessage());
                }
            }
        }
    }
}
